<script lang="ts" setup>
import { ref, watch } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { listByUserSelect, getResultOnTwoFilter } from '@/utils/format'
import { showConfirmDialog, type PickerConfirmEventParams } from 'vant'
import { getStringToNumber } from '@/utils'
import type { UserFiltersI } from '@/types/user'
import { useUserStore } from '@/stores/user'
import { createUserFiltersUtil, deleteUserFiltersUtil } from '@/AGC/utils/user_filters'
import { executeDeleteAllData, executeDeletePlanByDate } from '@/AGC/utils/user'

const store = useUserStore()
const userFilter = ref<UserFiltersI | undefined>(store.userFilter)
const router = useRouter()
const planInfo = ref({
  target: 0,
  sportAbility: '',
  eatScene: '',
  weight: '',
  targetWeight: '',
})
// 获取用户筛选条件
const getUserFilter = async () => {
  if (userFilter.value) {
    planInfo.value.target = userFilter.value.target
    planInfo.value.sportAbility = getResultOnTwoFilter(
      'sport_ability',
      userFilter.value.sport_ability,
    ) as string
    planInfo.value.eatScene = getResultOnTwoFilter(
      'eat_scene',
      userFilter.value.eat_scene,
    ) as string
    planInfo.value.weight = userFilter.value.weight
    planInfo.value.targetWeight = userFilter.value.target_weight
  }
}
getUserFilter()

// 规则生成规则
const rules = {
  sportAbility: [{ required: true, message: '请选择运动能力', trigger: 'blur' }],
  eatScene: [{ required: true, message: '请选择用餐场景', trigger: 'blur' }],
  weight: [{ required: true, message: '请选择体重', trigger: 'change' }],
  targetWeight: [
    { required: true, message: '请选择目标体重', trigger: 'change' },
    {
      validator: (rule: unknown, value: string, callback: (error?: Error) => void) => {
        const tempWeight = getStringToNumber(planInfo.value.weight, 'k')
        const tempValue = getStringToNumber(value, 'k')

        if (planInfo.value.target == 0) {
          if (tempWeight < tempValue) {
            callback()
          } else {
            callback(new Error('目标体重需要大于当前体重'))
          }
        } else {
          if (tempValue < tempWeight) {
            callback()
          } else {
            callback(new Error('目标体重需要小于当前体重'))
          }
        }
      },
    },
  ],
}
const formRef = ref<FormInstance>()
// 跳转至计划定制
const goToPlanCustom = async () => {
  if (store.userFilter) {
    showConfirmDialog({
      title: '温馨提示',
      message: '确定要清除计划的所有历史记录吗？',
    }).then(async () => {
      if (store.userFilter) {
        try {
          // 清除用户计划的所有历史记录
          await executeDeleteAllData()
          // 删除用户筛选条件
          await deleteUserFiltersUtil(store.userFilter)
          store.removeUserFilter()
          // 进行跳转
          router.replace('/plancustom')
        } catch (error) {
          ElMessage.error('重定计划失败')
          Promise.reject(error)
        }
      }
    })
  } else {
    // 进行跳转
    router.replace('/plancustom')
  }
}
const onSubmit = async () => {
  if (userFilter.value) {
    await formRef.value?.validate()
    // 整理参数
    userFilter.value.sport_ability = getResultOnTwoFilter(
      'sport_ability',
      planInfo.value.sportAbility,
    ) as number
    userFilter.value.eat_scene = getResultOnTwoFilter(
      'eat_scene',
      planInfo.value.eatScene,
    ) as number
    userFilter.value.weight = planInfo.value.weight
    userFilter.value.target_weight = planInfo.value.targetWeight

    try {
      // 调用接口
      await createUserFiltersUtil(userFilter.value)
      store.setUserFilter(userFilter.value)
      await executeDeletePlanByDate()
      ElMessage.success('微调计划成功')
    } catch (error) {
      ElMessage.error('微调计划失败')
      Promise.reject(error)
    }
  } else {
    ElMessageBox.alert('请先在 智能推荐 中进行计划定制哦', '温馨提示', {
      confirmButtonText: '确定',
      type: 'warning',
    })
  }
}
// Picker 显示数据
const columns = ref<{ text: string; value: string }[]>([])
const weightColumns = ref<{ text: string; value: string }[][]>([])
// Picker 显示类型
const showPopupType = ref<string>('')
watch(showPopupType, (value) => {
  if (value) {
    if (listByUserSelect(value) != undefined) {
      if (value == 'weight' || value == 'targetWeight') {
        weightColumns.value = listByUserSelect(value)! as { text: string; value: string }[][]
      } else {
        columns.value = listByUserSelect(value)! as { text: string; value: string }[]
      }
    }
  }
})
// Picker 确认事件
const onConfirm = ({ selectedValues }: PickerConfirmEventParams) => {
  switch (showPopupType.value) {
    case 'sportAbility':
      planInfo.value.sportAbility = selectedValues[0].toString()
      break
    case 'eatScene':
      planInfo.value.eatScene = selectedValues[0].toString()
      break
    case 'weight':
      planInfo.value.weight = selectedValues[0] + '.' + selectedValues[1] + 'kg'
      break
    case 'targetWeight':
      planInfo.value.targetWeight = selectedValues[0] + '.' + selectedValues[1] + 'kg'
      break
  }
  showPopupType.value = ''
}
</script>

<template>
  <el-card>
    <template #header>
      <div class="card-header">微调计划</div>
    </template>
    <span class="gradient-text">
      在这里可以
      <span class="keyword">微调</span>
      您的计划表哦~ 想定制或重新生成，可以
      <span class="link" @click="goToPlanCustom">点击这里</span>
    </span>
    <div class="update-body">
      <el-form label-width="90px" :model="planInfo" :rules="rules" ref="formRef">
        <el-form-item label="当前体重:" prop="weight">
          <div>
            <van-field
              v-model="planInfo.weight"
              is-link
              readonly
              placeholder="请选择当前体重(kg)"
              @click="showPopupType = 'weight'"
            />
            <van-popup :show="showPopupType == 'weight'" round position="center">
              <van-picker
                :columns="weightColumns"
                @cancel="showPopupType = ''"
                @confirm="onConfirm"
              />
            </van-popup>
          </div>
        </el-form-item>
        <el-form-item label="目标体重:" prop="targetWeight">
          <div>
            <van-field
              v-model="planInfo.targetWeight"
              is-link
              readonly
              placeholder="请选择目标体重(kg)"
              @click="showPopupType = 'targetWeight'"
            />
            <van-popup :show="showPopupType == 'targetWeight'" round position="center">
              <van-picker
                :columns="weightColumns"
                @cancel="showPopupType = ''"
                @confirm="onConfirm"
              />
            </van-popup>
          </div>
        </el-form-item>
        <el-form-item label="运动能力:" prop="sportAbility">
          <div>
            <van-field
              v-model="planInfo.sportAbility"
              is-link
              readonly
              placeholder="请选择运动能力"
              @click="showPopupType = 'sportAbility'"
            />
            <van-popup :show="showPopupType == 'sportAbility'" round position="center">
              <van-picker :columns="columns" @cancel="showPopupType = ''" @confirm="onConfirm" />
            </van-popup>
          </div>
        </el-form-item>
        <el-form-item label="用餐场景:" prop="eatScene">
          <div>
            <van-field
              v-model="planInfo.eatScene"
              is-link
              readonly
              placeholder="请选择用餐场景"
              @click="showPopupType = 'eatScene'"
            />
            <van-popup :show="showPopupType == 'eatScene'" round position="center">
              <van-picker :columns="columns" @cancel="showPopupType = ''" @confirm="onConfirm" />
            </van-popup>
          </div>
        </el-form-item>
        <el-form-item label-width="20px">
          <el-button type="primary" style="width: 100%; margin-top: 20px" @click="onSubmit"
            >微调计划</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.el-card {
  width: 30%;
  background-color: rgb(247, 248, 250);

  // 渐变改善版
  .gradient-text {
    color: black;
    font-size: 14px;
    text-align: center;
    font-family: 'Comic Sans MS', cursive, sans-serif;

    .keyword {
      color: rgb(5, 88, 229);
    }

    .link {
      color: rgb(5, 88, 229);
      text-decoration: underline; /* 下划线 */
      cursor: pointer; /* 鼠标指针 */
    }
  }

  .update-body {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 60px;

    .el-form {
      width: 80%;

      .MyRadio {
        ::v-deep(.el-form-item__label) {
          padding: 0 12px 0 0;
        }
      }

      ::v-deep(.el-form-item__label) {
        padding: 6px 12px 0 0;
      }

      .van-popup {
        width: 30%;
      }
    }
  }
}
</style>
